package com.nit.bike.service.bike.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nit.bike.dto.basic.BikeDTO;
import com.nit.bike.dto.bike.BikeRecordDTO;
import com.nit.bike.dto.utils.PagingDTO;
import com.nit.bike.dto.utils.TableReqDTO;
import com.nit.bike.dto.utils.TableRspDTO;
import com.nit.bike.entity.basic.BikeEntity;
import com.nit.bike.entity.bike.BikeRecordEntity;
import com.nit.bike.mapper.basic.BikeMapper;
import com.nit.bike.mapper.bike.BikeRecordMapper;
import com.nit.bike.service.bike.BikeRecordService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class BikeRecordServiceImpl implements BikeRecordService {
    @Resource
    private BikeRecordMapper bikeRecordMapper;
    @Resource
    private BikeMapper bikeMapper;

    @Override
    public TableRspDTO list4Table(TableReqDTO req) throws Exception {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<BikeRecordDTO> DTOs = bikeRecordMapper.list4Table(
                req.parseQueryParam("bikeId"),
                req.parseQueryParam("bikeRecordType"),
                req.getSortField(),
                req.getSortOrder()
        );
        return new TableRspDTO(new PagingDTO(
                req.getPageNo(),
                req.getPageSize(),
                new PageInfo<>(DTOs).getTotal(),
                DTOs));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(BikeRecordDTO bikeRecordDTO) throws Exception {
        MapperFactory factory = new DefaultMapperFactory.Builder().build();
        BikeRecordEntity entity = factory.getMapperFacade().map(bikeRecordDTO, BikeRecordEntity.class);
        // 更新状态
        BikeEntity bikeEntity = new BikeEntity();
        bikeEntity.setBikeId(entity.getBikeId());
        Integer recordType = entity.getBikeRecordType();
        if (recordType == 0) {
            bikeEntity.setBikeState(2);
        } else if (recordType == 1) {
            bikeEntity.setBikeState(0);
        } else {
            bikeEntity.setBikeState(3);
        }
        bikeEntity.setGmtModify(new Date());
        bikeMapper.updateByPrimaryKeySelective(bikeEntity);
        //新增bikeRecord
        entity.setGmtCreate(new Date());
        return bikeRecordMapper.insertSelective(entity);
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Integer update(BikeRecordDTO bikeRecordDTO) throws Exception{
//
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Integer remove(String ids) throws Exception {
//
//    }
}
